# -*- coding: utf-8 -*-
"""
Created on Wed Sep 26 19:30:58 2012

@author: witcher112
"""

import CPPparse
import pickle
def saveNamespace(ns,filename):
    filehandler=open(filename,'w')
    pickle.dump(ns,filehandler)
    filehandler.close()
def loadNamespace(filename):
    filehandler=open(filename,'r')
    ns=pickle.load(filehandler)
    filehandler.close()
    return ns
def getGlobalNamespace():
    ns=[]
    f=open("config.txt","r")
    for x in f.readlines():
        n=CPPparse.parse(x.replace("\n",""),1,False)
        ns.append(n)
    f.close()
    if len(ns)==0:
        return False
    retNs=ns[0]
    for x in ns:
        retNs.merge(x,True)
    return retNs


class ReplaceType:
    def __init__(self,new,old):
        self.data={"old":old,"new":new}
    def __setitem__(self,key,value):
        self.data[key]=value
    def __getitem__(self,key):
        return self.data[key]
    def oldEquals(self,a):
        if a["old"]["name"]==self["old"]["name"] and a["old"]["extra"]==self["old"]["extra"]:
            return True
        return False
class ReplaceTypeArray:
    data=[]
    def exist(self,x):
        for p in self.data:
            if p.oldEquals(x):
                return True
        return False
    def replace(self,typ):
        returnType=CPPparse._Type()
        returnType.data=typ.data
        for x in self.data:
            if x["old"]["name"]==returnType["name"] and x["old"]["extra"]==returnType["extra"]:
                returnType["name"]=x["new"]["name"]
                returnType["extra"]=x["new"]["extra"]
        for x in returnType["templates"]:
            x=self.replace(x)
        returnType.update()
        return returnType
    def append(self,new,old):
        self.appendType(self,ReplaceType(new,old))
    def appendType(self,x):
        if self.exist(x)==False:
            self.data.append(x)
def replaceAllTypes(gNs,data):
    for x in gNs.getObjects("Type"):
        x=data.replace(x)
    